<?php
function loadLib($sLibname) {
	switch ($sLibname) {
		case 'writeexcel':
			require_once "lib/writeexcel/class.writeexcel_workbook.inc.php";
			require_once "lib/writeexcel/class.writeexcel_worksheet.inc.php";
			break;
		default:
			ErrorHandler::addError('Library \"'.$sLibname.'\" not found');
	}
}

function msg($sText, $mParam = false) {
	static $sLangCache;
	$sLanguage = $_SESSION['oUserVars']['language'];
	
	if ($sLanguage == 'en') {
		return $sText;
	}
	
	if (is_string($mParam)) {
		$sView = $mParam;
	}
	else if ($mParam === true) {
		$sView = 'system';
	}
	else {
		$sView = $_REQUEST['sView'];
	}
	
	if (is_array(@$sLangCache[$sView]) && TRANSLATING_APP !== true) {
		return ($sLangCache[$sView][$sText] ? $sLangCache[$sView][$sText] : $sText);
	}
	
	if ($sView == 'system') {
		@include('include/lang/'.$sLanguage.'.lang.php');
	}
	else {
		list($sClass, $sBox) = split('-', $sView);
		@include('include/classes/'.$sClass.'/lang/'.$sLanguage.'/'.$sClass.'.'.$sBox.'.lang.php');
	}
	
	if (@$sLang[$sText]) {
		$sLangCache[$sView] = $sLang;
	}
	else if (TRANSLATING_APP === true) {
		$GLOBALS['system']['needs_translation'][$sView][] = $sText;
		$GLOBALS['system']['needs_translation'][$sView] = array_unique($GLOBALS['system']['needs_translation'][$sView]);
	}
	
	return (@$sLang[$sText] ? $sLang[$sText] : $sText);
}

function getMonths() {
	$sMonths = array(
		1 => msg('Jan', true),
		msg('Feb', true),
		msg('Mar', true),
		msg('Apr', true),
		msg('May', true),
		msg('Jun', true),
		msg('Jul', true),
		msg('Aug', true),
		msg('Sep', true),
		msg('Oct', true),
		msg('Nov', true),
		msg('Dec', true),
	);
	return $sMonths;
}

function pre($mArray) {
	print '<pre>'; print_r($mArray); print '</pre>';
}

function showMenuBar($oMenuBar) {
	print '<div class="menuBar">';
	foreach ($oMenuBar as $sID => $oMenuButton) {
		print '<a class="menuButton" href="" onClick="return buttonClick(event, \''.$sID.'\');" onMouseOver="buttonMouseover(event, \''.$sID.'\');">'.$oMenuButton['caption'].'</a>';
	}
	print '</div>';
	foreach ($oMenuBar as $sID => $oMenuButton) {
		print '<div style="visibility: hidden;" id="'.$sID.'" class="menu" onMouseOver="menuMouseover(event);">';
		foreach ($oMenuButton['menu'] as $oMenu) {
			switch ($oMenu['type']) {
				case 'sep':
					print '<div class="menuItemSep"></div>';
					break;
				case 'bool':
					print '<a class="menuItem" href="'.$oMenu['url'].'">';
					print '<img src="images/'.($oMenu['checked'] ? 'check_full.png' : 'check_empty.png').'" style="padding: 0px 4px 0px 0px;" border="0">';
					print $oMenu['caption'];
					print '</a>';
					break;
				case 'url':
					print '<a class="menuItem" href="'.$oMenu['url'].'" '.(@$oMenu['onclick'] ? 'onClick="'.$oMenu['onclick'].'"' : '').'>'.$oMenu['caption'].'</a>';
			}
		}
		print '</div>';
	}
}

// Just a handy header-function for our mail handlers.
function mailHeaders($sReplyTo = '') {
	$oUsers = UserHandler::getUsers();
	$sReplyTo = ($sReplyTo ? $sReplyTo : $oUsers[$_SESSION['rid']]->sEmail);
	$sHeaders = "From: mijob@".MAIL_HOSTNAME."\n";
	$sHeaders .= "Reply-To: $sReplyTo\n";
	$sHeaders .= "Content-Type: text/plain; charset=ISO-8859-15\n";
	$sHeaders .= "Content-Transfer-Encoding: 8bit\n";
	return $sHeaders;
}

// This function shows a job selector drop-down box, with optional parameters.
function jobSelector($sInputName = 'iJob', $iSelected = 0, $sOnClick = '') {
	if (!$iSelected) {
		$iSelected = $_SESSION['iJobID'];
	}
	$oJobs = JobHandler::getJobs();
	$oJobgroups = JobgroupHandler::getJobgroups();
	if (count($oJobs) == 0) {
		print '<select disabled><option>[ '.msg('None', true).' ]</option></select>';
		print '<input type="hidden" name="iJobID" value="0">';
	}
	else {
		print '<select name="'.$sInputName.'" onChange="'.$sOnClick.'">';
		$iGroupedJobs = array();
		foreach ($oJobgroups as $oThisJobgroup)
		{
			print '<option class="separator" value="0">'.$oThisJobgroup->sName.'</option>';
			$iJobs = $oThisJobgroup->getJobs();
			foreach ($iJobs as $iThisJob)
			{
				print '<option class="listentity" value="'.$oJobs[$iThisJob]->iID.'"'.($oJobs[$iThisJob]->iID == $iSelected ? ' selected' : '').'>'.$oJobs[$iThisJob]->sName.'</option>';
				$iGroupedJobs[] = $iThisJob;
			}
		}
		if (count($oJobgroups) > 0 && count($oJobs) != count($iGroupedJobs))
		{
			print '<option class="separator" value="0">'.msg('Ungrouped project', true).'</option>';
		}
		foreach ($oJobs as $oThisJob)
		{
			if (!in_array($oThisJob->iID, $iGroupedJobs))
			{
				print '<option class="listentity" value="'.$oThisJob->iID.'"'.($oThisJob->iID == $iSelected ? ' selected' : '').'>'.$oThisJob->sName.'</option>';
			}
		}
		print '</select>';
	}
}

function __autoload($sClassname) {
	if (substr($sClassname, -7) == 'Handler') {
		$sClass = strtolower(substr($sClassname, 0, -7));
		require('include/classes/'.$sClass.'/'.$sClass.'.handler.php');
	}
	else if (substr($sClassname, -3) == 'DAO') {
		$sClass = strtolower(substr($sClassname, 0, -3));
		require('include/classes/'.$sClass.'/'.$sClass.'.dao.php');
	}
	else if (substr($sClassname, -9) == 'Exception') {
		$sClass = strtolower(substr($sClassname, 0, -9));
		require('include/exceptions/'.$sClass.'.exception.php');
	}
	else if ($sClassname == "Requester") {
		require('include/baseclasses/requester.baseclass.php');
	}
	else {
		$sClass = strtolower($sClassname);
		require('include/classes/'.$sClass.'/'.$sClass.'.class.php');
	}
}

function loadBox($sView, $sArguments = '') {
	list($sClass, $sBox) = split('-', $sView);
	if ($sArguments) {
		$sEntities = split('\&', $sArguments);
		foreach ($sEntities as $sThisEntity) {
			list($sVarname, $sValue) = split('=', $sThisEntity);
			$_REQUEST[$sVarname] = $sValue;
		}
	}
	$sOldView = (@$_REQUEST['sView'] ? $_REQUEST['sView'] : '');
	$_REQUEST['sView'] = $sView;
	$sFilename = 'include/classes/'.$sClass.'/ui/'.$sClass.'.'.$sBox.'.ui.php';
	if (is_file($sFilename)) {
		require($sFilename);
	}
	else {
		require('include/classes/appconfig/ui/appconfig.missingview.ui.php');
	}
	$_REQUEST['sView'] = $sOldView; // <-- What's this? -helgi@binary.is, 2012-03-12
}

// DB-friendly booleanizer.
function boolize($sValue)
{
	return ($sValue ? 1 : 0);
}

// This function returns the current timestamp, and stores it in memory.
// It can then be used again and again and will always return the first
// timestamp that was created with it, in the script currently running.
function thisSecond()
{
	static $iThisSecond;
	if ($iThisSecond)
	{
		return $iThisSecond;
	}
	else
	{
		$iThisSecond = mktime();
		return $iThisSecond;
	}
}

// A function for showing dates and times, only showing what's needed.
// It will, for example, skip the year if the returned year is the present year.
function coolDate($iTime, $bShowSeconds = false, $bSeperateClock = false)
{
	if (!$iTime)
		return "";
	
	$iThisYear = date('Y');
	$sThisDayMonth = date('j. M');
	
	$iYear = date('Y', $iTime);
	$sDayMonth = date('j. M', $iTime);
	
	$sFinal = date(($bShowSeconds ? 'H:i:s' : 'H:i'), $iTime).($bSeperateClock ? '<br>' : '');
	
	if ($sDayMonth != $sThisDayMonth || $iTime < thisSecond() - 86400)
		$sFinal .= ' '.$sDayMonth;
	
	if ($iYear != $iThisYear)
		$sFinal .= ', '.$iYear;
	
	return $sFinal;
}

function coolMonth($iTime)
{
	$iThisYear = date('Y');
	$iYear = date('Y', $iTime);

	$sFinal = date('j. M', $iTime);

	if ($iThisYear != $iYear) {
		$sFinal .= ', '.$iYear;
	}
	
	return $sFinal;
}

function calcHours($iTime, $bCool = false)
{
	if ($bCool)
	{
		$iMinutes = round($iTime / 60);
		$iHours = floor($iMinutes / 60);
		$iMinutesLeft = $iMinutes - ($iHours * 60);
		
		if (strlen($iHours) == 1)
			$iHours = '0'.$iHours;
		if (strlen($iMinutesLeft) == 1)
			$iMinutesLeft = '0'.$iMinutesLeft;
		
		return $iHours.':'.$iMinutesLeft;
	}
	else
	{
		return round($iTime / 60 / 60, 2);
	}
}

// Handy-function to check if the current hit is a POST or not.
function isPosted() {
	return ($_SERVER['REQUEST_METHOD'] == 'POST');
}

// A substitute for mysql_query(), for keeping track of queries and calculating speeds.
// Mostly meant for debugging and optimizing database queries.
/* Deprecated 2011-12-26: Should be ported to DataHandler at some point.
function doQuery($sQueryString = "", $sDescr = "")
{
	static $sQueries;
	static $iTimes;
	if (!is_array($sQueries))
	{
		$sQueries = array();
	}
	if (!is_array($iTimes))
	{
		$iTimes = array();
	}
	
	if (!$sQueryString)
	{
		$iArrayCounts = array_count_values($sQueries);
		?>
		<div id="layer_debug_sql" class="hidden" style="visibility: visible; position: absolute;">
		<table cellspacing="0">
		<?php
		$iTotalTime = 0;
		for ($i = 0; $i < count($sQueries); $i++)
		{
			$iTotalTime += $iTimes[$i];
			?>
			<tr>
				<td class="listentity"><?php print ($iArrayCounts[$sQueries[$i]] > 1 ? '<span class="error">'.($i + 1).'</span>' : ($i + 1)) ?></td>
				<td class="listentity"><?php print nl2br(str_replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $sQueries[$i])) ?></td>
				<td class="listentity"><?php print $iTimes[$i] ?></td>
			</tr>
			<?php
		}
		?>
			<tr>
				<td class="boxbody center" colspan="2"><input type="button" value="� lagi" onClick="layerHide('layer_debug_sql');"></td>
				<td class="boxbody center"><?php print $iTotalTime ?></td>
			</tr>
		</table>
		</div>
		<?php
	}
	else
	{	
		array_push($sQueries, $sQueryString);
		$iBegin = microtime(true);
		$oQuery = @mysql_query($sQueryString);
		array_push($iTimes, microtime(true) - $iBegin);
		if (!$oQuery && @$_REQUEST['sView'] != 'appconfig-setup')
		{
			ErrorHandler::addError('MySQL: '.mysql_error());
		}
		return $oQuery;
	}
}
*/

?>
